<?php

namespace Catmes\LayAdmin\Components;

class Template
{

    protected static $instance;

    protected $templatePath = '';

    protected $viewPath = '';

    protected $csrfToken = '';
    protected $csrfTokenField = '_token';

    protected function __construct()
    {
        $defaultPath = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'templates';
        $this->templatePath = $defaultPath;
        $this->viewPath = $defaultPath;
    }

    public function setCsrfToken($token, $csrfTokenField="_token"):self{
        $this->csrfToken = $token;
        $this->csrfTokenField = $csrfTokenField;
        return $this;
    }

    public function getCsrfToken():string{
        return $this->csrfToken;
    }

    public function getCsrfTokenField():string{
        return $this->csrfTokenField;
    }

    /**
     * 调用此静态方法获得对象单例。 避免多次实例化。
     * 一次实例化，即可多处复用。
     */
    public static function getInstance() :self
    {
        if(!self::$instance instanceof self){
            // 单例模式故，此代码一个页面生命周期内仅执行一次。
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function setViewPath($path):self{
        $this->viewPath = $path;
        return $this;
    }
    public function getViewPath():string{
        return $this->viewPath;
    }

    public function setTemplatePath($path):self{
        $this->templatePath = $path;
        return $this;
    }
    public function getTemplatePath() :string {
        return $this->templatePath;
    }

    public function getFrameFile() :string {
        return $this->templatePath . '/lay_frame.php';
    }

    public function view($filename, $vars=[]){
        $filepath = strpos($filename, '/')===0 ? $filename : $this->viewPath."/".$filename;
        return $this->display($filepath, $vars);
    }
    public function render($filename, $vars=[]){
        $filepath = strpos($filename, '/')===0 ? $filename : $this->templatePath."/".$filename;
        return $this->display($filepath, $vars);
    }

    protected function display(string $template, array $vars){
        ob_start();
        extract($vars);
        require $template;
        return ob_get_clean();
    }
}
